package org.dromara.common.json.fastjson.filters;

import com.alibaba.fastjson.serializer.ValueFilter;

import java.lang.reflect.Field;
import java.util.Collection;

/**
 * Created by       mac
 * Create Date      2020/12/11
 * Version          1.0.0
 * Description:
 */
public class NullValueFilter implements ValueFilter {

    @Override
    public Object process(Object object, String name, Object value) {
        if (value == null) {
            Class clazz = object.getClass();
            Field field = getFiledRecursive(clazz, name);
            if (field == null) return null;
            Class<?> fieldType = field.getType();

            field.setAccessible(true);

            if (Collection.class.isAssignableFrom(fieldType)) {
                return value;
            }
            else if (fieldType.isArray()) {
                return new Object[0];
            }
            else{
                return "";
            }

        }
        return value;
    }

    private Field getFiledRecursive(Class clazz, String name) {
        try{
            return clazz.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            Class superClazz = clazz.getSuperclass();
            if (superClazz.equals(Object.class)) return null;
            return getFiledRecursive(superClazz, name);
        }
    }
}
